package com.surfilter.massdata.spark.task.daystati;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.sql.DataFrame;
import org.apache.spark.sql.Row;

import scala.Tuple2;

import com.act.sparkanalyz.service.impl.SparkService.OutQueueEntity;
import com.act.sparkanalyz.task.ISparkTask;
import com.surfilter.massdata.spark.bean.SAN061;
import com.surfilter.massdata.spark.util.CommonUtils;
import com.surfilter.massdata.spark.util.DateUtil;
import com.surfilter.massdata.spark.util.URLUtil;

/**
 * 网站后缀访问量
 * 本省接入网站各域名后缀访问量变化统计（要求是省内接入网站，即dip在BR2002中存在）
 */
public class DomainAnalyzTask_New  implements ISparkTask{
	
	private static final Log log = LogFactory.getLog(DomainAnalyzTask_New.class);
	
	private static final long serialVersionUID = 1L;
	private static Pattern IP_PATTERN = Pattern.compile("(\\d{1,3}\\.){3}(\\d{1,3})");
	private String outName;

	@Override
	public List<OutQueueEntity> execute(Map<String, DataFrame> dataFrames, Map<String, String> commandMap) {
		long start=System.currentTimeMillis();
		log.info("==============DomainAnalyzTask begin====================");
		List<OutQueueEntity> outList = new ArrayList<OutQueueEntity>();
		try{
			DataFrame dipFrame = dataFrames.get("day_domain");
			
		    JavaPairRDD<String, Long> domainCounts = getDomainCounts(dipFrame);
		    
	        String dayStr = commandMap.get("-d");
	        Date date = DateUtil.getExecDate(DateUtil.getYesterday(),dayStr);
	        
	        JavaRDD<SAN061> rdd = createRdd(domainCounts, date);
	    	DataFrame df = dipFrame.sqlContext().createDataFrame(rdd, SAN061.class);
	    	//df.registerTempTable(outName); //插入到hive中需要使用临时表
	    	outList.add(new OutQueueEntity(outName, df));
	    	
	    	CommonUtils.deleteTaskTableData("SAN061", date, "WEBSITE_COUNT_SUFFIX", 0, "day");
		}catch(Exception e){
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
		}
		
		long end=System.currentTimeMillis();
		double min=(end-start)*1.0/(1000*60);
		System.out.println("DomainAnalyzTask_New1111:exectime: "+min+" min............");
		
		return outList;
	}

	@SuppressWarnings("serial")
	private JavaRDD<SAN061> createRdd(JavaPairRDD<String, Long> domainCounts, final Date date) {
		JavaRDD<SAN061> rdd = domainCounts.mapPartitions(new FlatMapFunction<Iterator<Tuple2<String,Long>>, SAN061>() {

			@Override
			public Iterable<SAN061> call(Iterator<Tuple2<String, Long>> it){
				List<SAN061> list = new ArrayList<SAN061>();
				while(it.hasNext()){
					Tuple2<String, Long> tuple = it.next();
					String domain = tuple._1;
					if(StringUtils.isNotBlank(domain)){
		        		SAN061 sa = new SAN061();
		        		sa.setYear(DateUtil.getCurrentYear(date));
		        		sa.setHalf_year(DateUtil.getHalfYear(date));
		        		sa.setQuarter(DateUtil.getQuarter(date));
		        		sa.setMonth(DateUtil.getCurrentMonth(date));
		        		sa.setWeek(DateUtil.getCurrentWeek(date));
		        		sa.setDay(DateUtil.getCurrentDay(date));
		        		sa.setBuss_type("WEBSITE_COUNT_SUFFIX");
		        		sa.setBuss_value(domain);
		        		sa.setCount_value(tuple._2);
		        		sa.setSta_range(0);
		        		list.add(sa);
		        	}
				}
				return list;
			}
		});
		return rdd;
	}

	private JavaPairRDD<String, Long> getDomainCounts(DataFrame resultFrame) {
		
		JavaRDD<String> domainSuffix = resultFrame.toJavaRDD().map(new Function<Row,String>(){
			private static final long serialVersionUID = 1L;
			@Override
			public String call(Row row){
				String result = "";
				String domain = row.getAs("domain");
				try{
					String topDomain = URLUtil.getDomainName("http://" + domain);
					if(StringUtils.isNotBlank(topDomain)){
						if(IP_PATTERN.matcher(topDomain).matches()){//判断是否为IP
							result =  topDomain;
						}else{
							result = topDomain.substring(topDomain.indexOf(".")+1,topDomain.length());
						}
					}else{
						//表示域名不符合规则
						if(domain.indexOf(".") > 0){
							result = domain.substring(domain.indexOf(".") + 1,domain.length());
						}else{
							result = domain;
						}
					}
				}catch(Exception e){
					if(log.isErrorEnabled()){
						log.error(e.getMessage(),e);
					}
				}
				return result + "@" + row.getAs("visit_count");
			}});
		
        JavaPairRDD<String,Long> domainPair = domainSuffix.mapToPair(new PairFunction<String,String,Long>(){
			private static final long serialVersionUID = 1L;
			@Override
			public Tuple2<String, Long> call(String value){
				try{
					String[] valueStr = value.split("@");
					String domain = valueStr[0];
					long count = Long.parseLong(valueStr[1]);
					Tuple2<String,Long> tuple = new Tuple2<String,Long>(domain,count);
					return tuple;
				}catch(Exception e){
					if(log.isErrorEnabled()){
						log.error(e.getMessage(),e);
					}
				}
				return new Tuple2<String,Long>("",0L);
			}});
        JavaPairRDD<String,Long> domainCounts = domainPair.reduceByKey(new Function2<Long,Long,Long>(){
			private static final long serialVersionUID = 1L;
			@Override
			public Long call(Long x, Long y)throws Exception {
				return x+y;
			}});
		return domainCounts;
	}

}
